<html>
   
<!--
/*
* Copyright (C) 2005-2013 University of Sydney
*
* Licensed under the GNU License, Version 3.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/

/**
*   Heurist Mobile (html version) launch page, Aug 2010 - Mar 2011
*
* @author      Artem Osmakov   <artem.osmakov@sydney.edu.au>
* @copyright   (C) 2005-2013 University of Sydney
* @link        http://sydney.edu.au/heurist
* @version     3.1.0
* @license     http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @package     Heurist academic knowledge management system

*    manifest="cache.manifest"

*/
-->
    <head>
        <title>Heurist Mobile for tablet/phone</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta content="width=device-width; initial-scale=1.0; maximum-scale=2.0; user-scalable=1;" name="viewport">

        <link rel="apple-touch-icon-precomposed" href="icon.png"> 
        <link rel="apple-touch-startup-image" href="startup.png">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">

        <!-- Legacy: for use with Google Maps Vsn 2 -->
        <!-- <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> -->
        <!-- <script src="http://hapi.heuristscholar.org/load?instance=dos-sandbox&key=f0380e79c4b03a762b0f84f4aa0a1315367d9bd1"></script>    Heurist API Key -->
        <!-- f0380e79c4b03a762b0f84f4aa0a1315367d9bd1 is key for dos-sandbox on Heuristscholar.org -->

        <script type="text/javascript" src="OpenLayers.debug.js"></script>

        <script src="utils.js"></script>
        <script src="main.js"></script>
        <script src="mapping.js"></script>

        <style type="text/css" media="screen">
            .entryPage {
                border-width: 3px;
                border-style: outset;
            }
            .entry {
                border-width: 3px;
                border-style: outset;
                padding: 2px;
            }            
        </style>

        <!-- -->
        <link type="text/css" href="tempJQueryUI/css/ui-lightness/jquery-ui-1.8.11.custom.css" rel="stylesheet" />
        <script type="text/javascript" src="tempJQueryUI/js/jquery-1.5.1.min.js"></script>
        <script type="text/javascript" src="tempJQueryUI/js/jquery-ui-1.8.11.custom.min.js"></script>

        <link href="mobile.css" rel="stylesheet" type="text/css">
        
        <script type="text/JavaScript">

            // NOT USED calculate distance between two coordinates
            function calculateDistance(lat1,lon1,lat2,lon2) {
                var R = 6371000; // earth's radius in meters
                var dLat = (lat2-lat1) * Math.PI / 180;
                var dLon = (lon2-lon1) * Math.PI / 180;
                var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
                Math.sin(dLon/2) * Math.sin(dLon/2);
                var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                var d = R * c;
                return d;

                // or google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);
                // and &libraries=geometry

            }


            var tours = null,
            _curr_tour = null,
            _curr_tour2 = null,
            _curr_stop = null,
            _reloadToursOnMap = true,
            _sMainTitle,
            map_ol = null,
            map_stop = null,
            RT_TOUR = 22,
            RT_MEDIA = 5,
            RT_NOTE = 2;   // Hard-coded Tour record type ??? Need to sue a concept code, not a hardcoded internal code

            var 
            _mapoptions = {colors:['#ff0000','#008000','#7FFF00','#006400','#FF1493','#DAA520','#CD5C5C','#66CDAA'], show_bbox:true, show_paths:true, show_start:true, minLng:0, maxLng:0, minLat:0, maxLat:0 },
            url_mainlist = null,
            url_report_media,
            url_report_entries,
            _isCacheUpdateForce = false,
            _serverVersion = 0,
            _localVersion = 0,
            _isOnline = false,
            _position = null, //position.coords.latitude, position.coords.longitude
            _useCacheIfOnline = true;
            
            var _basePath;


            /**
            *
            */
            function init(e) // Initialise the application
            {
                //utils.isOnline = true;
                //init_continue_2(null);
                
                utils.checkNetworkStatus(init_continue_1);
            }                
                
            function init_continue_1(){
                if(true || !utils.isOnline){
                    init_continue_2(null);    
                }else{
                    $("#nearbyTours").html("<strong>Detecting geolocation...</strong>");
                    
                    utils.getCurrentPosition(init_continue_2)  
                }
            }
            
            function init_continue_2(position){

                $("#nearbyTours").html("<strong>Loading tours......</strong>");
                
                //parse parameters (dbname) and load configuration file
                var params = utils.parseParams(null);
                if(utils.isnull(params.db)) {
                    params.db = "DoS_Tours";
                }

                _isOnline = utils.isOnline;
                _position = position;

                if(_isOnline){
                    loadConfig(params.db);
                }
                
                utils.useCacheIfOnline = _useCacheIfOnline;

                var cachedtours = null;
                //by default we load tours from cache
                if(window.localStorage)
                {
                    _localVersion = Number(window.localStorage.getItem("version"));
                    if(isNaN(_localVersion)) _localVersion = 0;

                    if (_useCacheIfOnline || !isOnline){
                        cachedtours = localStorage.getItem("alltours");
                        //cache is empty
                        if( (!_isOnline) && utils.isempty(cachedtours)){
                            showMsgPage("Sorry. You are offline and no tour data have been downloaded on your device", "Try once more", init);
                            return;
                        }
                    }
                }

                loadTours(cachedtours);

                // Artem: TODO: please add the date of the version to the information here 
                // "Vsn 8" doesn't tell you anything, "Vsn 8, 17 July 2010" tells you it is a long way out of date
                if (_isOnline && _serverVersion>_localVersion && _isCacheUpdateForce){
                    showMsgPage( ((_localVersion==0)?"<p/>There are no tours stored on your device":("Current stored data Vsn #"+_localVersion))+
                        "<p/>Tour data available on server: Vsn #"+_serverVersion+"<p/>",
                        "Download updated tour data", cacheSeedFromServer);
                }
            }

            /**
            *
            */
            function loadTours(cache){ 

                //request and parse tours as HML from H3 instance
                tours = new Tours(url_mainlist, cache);

                var err = tours.getError();

                if(!utils.isnull(err)){
                    showMsgPage(err, "Please try again", init);
                    return;
                }

                var list = document.getElementById("nearbyTours");
                list.innerHTML = tours.getTourList(_position,0);
                
                //list = document.getElementById("allTours");
                //list.style.display = 'none';
                
                if(utils.isnull(_position) || $(".nearby").length==0 ){ //geolocation is not defined or all remote
                    $("#toursAllOrNearby").css('display','none'); //hide button
                }else{ 
                    //list.innerHTML = tours.getTourList(null,1);
                    showAllOrNearby();
                }
                
                //execute script to obtain thumbnails
                execScript(list);

                _reloadToursOnMap = true;
                _curr_tour = null;
                _curr_tour2 = null;
                _curr_stop = null;
            }

            /**
            *
            */
            function loadConfig(db){
                
                
                _basePath = utils.getBasePath();
                
                var configUrl = _basePath + "records/files/downloadFile.php?mobcfg=1&db="+db;

                var xmlDoc = utils.getcontent(configUrl, true);

                if(utils.isnull(xmlDoc)){
                    showMsgPage("Unable to load the configuration file. You will need an internet connection. If issue persists, please contact development team", "Try again", init);
                    return;
                }

                var s = utils.getnode("title", true, xmlDoc);
                if(!utils.isempty(s)){
                    _sMainTitle = s;
                    document.getElementById("header").innerHTML = s;
                }else{
                    _sMainTitle = document.getElementById("header").innerHTML;
                }
                s = utils.getnode("version", true, xmlDoc);
                if(!utils.isempty(s)){
                    _serverVersion = Number(s);
                }
                
                _isCacheUpdateForce = utils.getnode_bool("forceCacheUpdate", xmlDoc, false);
                _useCacheIfOnline = utils.getnode_bool("useCacheIfOnline", xmlDoc, true);
                
                var cmap = utils.getnode("map", false, xmlDoc);
                if(cmap){
                    var bbox = utils.getnode("BoundingBox", false, cmap);

                    _mapoptions.minLng = Number(bbox.getAttribute("minx"));
                    _mapoptions.maxLng = Number(bbox.getAttribute("maxx"));
                    _mapoptions.minLat = Number(bbox.getAttribute("miny"));
                    _mapoptions.maxLat = Number(bbox.getAttribute("maxy"));
                    
                    _mapoptions.show_bbox = utils.getnode_bool("showBBoxes", cmap, true);
                    _mapoptions.show_paths = utils.getnode_bool("showPaths", cmap, true);
                    _mapoptions.show_start = utils.getnode_bool("showStartPoint", cmap, true);
                    
                    var j;
                    for (j =  1; j < 10; j++) {
                        s = utils.getnode("color"+j, true, cmap);
                        if(!utils.isempty(s)){
                            _mapoptions.colors[j-1] = s;
                        }
                    }
                    
                    _mapoptions.style_segment = utils.getnode_style("style_segment", cmap);
                    _mapoptions.style_bbox = utils.getnode_style("style_bbox", cmap);
                    _mapoptions.style_marker_start = utils.getnode_style("style_marker_start", cmap);
                    _mapoptions.style_marker_starttour = utils.getnode_style("style_marker_starttour", cmap);
                    _mapoptions.style_marker = utils.getnode_style("style_marker", cmap);
                    
                }

                //get urls for media and entry tabs
                var cpage = utils.getnode("page", false, xmlDoc);
                if(cpage){
                    url_mainlist = utils.getnode("mainlist", true, cpage);
                    url_report_media = utils.getnode("media", true, cpage);
                    url_report_entries = utils.getnode("entries", true, cpage);
                }

                if(utils.isempty(url_mainlist)){
                    url_mainlist =  _basePath+"export/xml/flathml.php?w=all&a=1&depth=1&q=type:"+RT_TOUR+"&db="+db;
                }
                if(utils.isempty(url_report_media)){
                    url_report_media =  _basePath+"viewers/smarty/showReps.php?ver=1&w=all&stype=&db="+db+"&q=type:"+RT_MEDIA+" ids:[recids]&publish=1&debug=0&template=media viewer.tpl";
                }
                if(utils.isempty(url_report_entries)){
                    url_report_media =  _basePath+"viewers/smarty/showReps.php?ver=1&w=all&stype=&db="+db+"&q=type:"+RT_NOTE+" ids:[recids]&publish=1&debug=0&template=media viewer.tpl";
                }
                
            } // function loadConfig(db)


            //
            //
            //
            function showMsgPage(msg, btn, callback){
                showPage("message");
                var btnInit = document.getElementById('btnMessage');
                var divInit = document.getElementById('divMessage');
                divInit.innerHTML = msg;
                btnInit.innerHTML = btn;
                btnInit.onclick = callback;
            }

            /**
            * Switch between main tabs
            */
            function showPage(tabname) {
                document.getElementById("listPage").style.display = (tabname=="list")?"block":"none";
                document.getElementById("mapPage").style.display = (tabname=="map")?"block":"none";
                document.getElementById("segmentPage").style.display = (tabname=="stop")?"block":"none";
                document.getElementById("cachePage").style.display = (tabname=="cache")?"block":"none";
                document.getElementById("messagePage").style.display = (tabname=="message")?"block":"none";

                if(tabname!="stop"){
                    document.getElementById("map_stop").style.display = "none";
                }

                if(tabname=="list" || tabname=="message" || tabname=="cache" || !_curr_tour){
                    document.getElementById("header").innerHTML = _sMainTitle;
                }else{
                    document.getElementById("header").innerHTML = _curr_tour.title;
                }
            }


            /**
            *
            */
            function showPathDesc(tourid){
                var ele = document.getElementById("pathDesc"+tourid);

                if(ele.className == "pathwayDescription") {
                    ele.className = "hiddenPathwayDescription";
                    ele.parentNode.parentNode.style.height = "35px";
                } else {
                    ele.className = "pathwayDescription";
                    ele.parentNode.parentNode.style.height = "auto";
                }
            }

            /**
            *
            */
            function initMapMain(){
                // initialize main map
                if(map_ol==null){
                    showPage("map");                                                                    
                    map_ol = new Map_OpenLayers("map_canvas", _mapoptions);
                    map_ol.setCallback(startVisit);
                }
            }

            /**
            *  Show all tours on map - start Stop and connections
            *  selected tour in red
            *
            *  tourid - id of selected tour
            */
            function showAllToursOnMap(tourid)
            {
                if(tourid!=null){
                    var tour = tours.getTourById(tourid);
                    _curr_tour = tour;
                    _curr_stop = null;
                }else if (_curr_tour){
                    tourid = _curr_tour.id;
                }
                
                if(!_curr_tour.has_geo){
                     gotoStop(0);
                     return;
                }
                
                
                showPage("map");

                document.getElementById("header").innerHTML = _curr_tour.title;

                //if(utils.isnull(tourid) || utils.isnull(_curr_tour) || _curr_tour.id!=tourid){ //
                if(_reloadToursOnMap){

                    initMapMain();

                    _reloadToursOnMap = false;

                    //clear previous map
                    map_ol.clearAll();
                    map_ol.loadAllTours(null, tours.getTours());
                }

                if(_curr_tour.stops.length>0){
                    map_ol.zoomToStop( _curr_tour.stops[0] );
                }
            }//


            /**
            *
            */
            function showTourOnMap(tour)
            {
                //clear previous map
                if(utils.isnull(_curr_tour2) || _curr_tour2.id!=tour.id){

                    if(map_stop == null){
                        map_stop = new Map_OpenLayers("map_stop", _mapoptions);
                        map_stop.setCallback(gotoStop);
                        map_stop.updateSize();
                    }

                    _curr_tour2 = tour;
                    map_stop.clearAll();
                    map_stop.loadTour(tour);

                }else if(!utils.isnull(_curr_tour2)){
                    //map_stop.zoomToTour(tour, gotoStop);
                }

            }//

            //
            function startVisit(tourid)
            {
                var tour = tours.getTourById(tourid);
                _curr_tour = tour;
                _curr_stop = null;
                _reloadCurrToursMap = true;
                gotoStop(0);
            }

            var __currentTab = 0;

            /**
            * swith to View tab and fill subtabs
            *
            * stopid -1 next, -3 previous, 0 first, >0 search by ID
            */
            function gotoStop(stopid){

                if(utils.isnull(_curr_tour) ||  utils.isnull(_curr_tour.stops_order) || _curr_tour.stops_order.length<1) {
                    showPage("list");
                    return;
                }

                showPage("stop");

                var cindex = 0;

                if(stopid>0){ //search by id
                    cindex = tours.getStopIndex(_curr_tour, stopid);
                    
                }else if(stopid<0 && !utils.isnull(_curr_stop)){ //next or prev
                    
                    cindex = tours.getStopIndex(_curr_tour, _curr_stop.id);
                    cindex = cindex + stopid + 2;
                }
                if(cindex<0  || cindex>_curr_tour.stops_order.length-1) {
                    cindex=0;
                }
                
                var new_stopid =  _curr_tour.stops_order[cindex];

                if(_curr_stop && new_stopid == _curr_stop.id){ //the same
                    return;
                }

                _curr_stop =  tours.getStopById(_curr_tour, new_stopid);

                $(function() {
                    $( "#tabs" ).tabs();
                    $('#tabs').bind('tabsselect', function(event, ui) {
                        __currentTab = ui.index;
                        document.getElementById("map_stop").style.display = (__currentTab===1 && _curr_tour.has_geo)?"block":"none";
                        if(__currentTab===1 && _curr_tour.has_geo){
                            showTourOnMap(_curr_tour);
                        }
                    });
                });

                if(__currentTab===1 && _curr_tour.has_geo){
                    document.getElementById("map_stop").style.display = "block";
                    //
                    showTourOnMap(_curr_tour);
                    //zoom to current stop
                    map_stop.zoomToStop(_curr_stop);
                }


                document.getElementById("activeStopTitle").innerHTML = _curr_stop.title; //+"  "+_curr_stop.id; //_curr_tour.title;
                //document.getElementById("activeStopTitle").innerHTML ="<i><strong>(" + _curr_stop.title + ")</strong></i><br/>";
                var stopTitle = ""; //"<div class='activeStopTitle2'>(" + _curr_stop.title + ")</div>";


                var tab1 = document.getElementById("tab-1");
                var tab2 = document.getElementById("tab-2");
                var tab3 = document.getElementById("tab-3");
                var tab4 = document.getElementById("tab-4");
                var tab5 = document.getElementById("tab-5");

                tab1.innerHTML = stopTitle;
                if(!utils.isempty(_curr_stop.thumbnail)){
                    tab1.innerHTML += '<div><img src="' + _curr_stop.thumbnail + '" style="max-width:100%"></img></div><br /><br />';
                }
                if(!utils.isempty(_curr_stop.description)){
                    tab1.innerHTML += "<u>Description:</u><br />" + _curr_stop.description + "<br /><br />";
                }

                if(_curr_tour.has_geo) {
                    tab2.innerHTML = "";
                }else{
                    tab2.innerHTML = "This tour has not been mapped";
                }

                //connection to next stop                
                var connection = tours.getConnectionByStartStopId(_curr_tour, _curr_stop.id);
                tab3.innerHTML = connection?(connection.title+"<br/>"+connection.description):"";//_curr_stop.media;
                if(utils.isempty(tab3.innerHTML)){
                    if(_curr_tour.connections.length==0){
                        tab3.innerHTML = "No routes defined for this tour";
                    }else{
                        tab3.innerHTML = connection ?"there are no description for route to next stop" :"This stop is final for tour";
                    }
                }else{
                    execScript(tab3);
                }
                tab3.innerHTML = stopTitle + tab3.innerHTML;
                
                
                //@todo - load content of tab on their selection only
                if(utils.isnull(_curr_stop.media)){
                    _curr_stop.media = getMediaReport(url_report_media, _curr_stop.assets);
                }
                tab4.innerHTML = _curr_stop.media;
                if(utils.isempty(tab4.innerHTML)){
                    tab4.innerHTML = "there are not media content for this stop";
                }else{
                    execScript(tab4);
                }
                tab4.innerHTML = stopTitle + tab4.innerHTML;

                if(utils.isnull(_curr_stop.entries)){
                    _curr_stop.entries = getMediaReport(url_report_entries, _curr_stop.assets);
                }
                tab5.innerHTML = _curr_stop.entries;
                if(utils.isempty(tab5.innerHTML)){
                    tab5.innerHTML = "there are not entries for this stop";
                }else{
                    execScript(tab5);
                }
                tab5.innerHTML = stopTitle + tab5.innerHTML;
            }

            //
            //
            //
            function getMediaReport(url, assets){
                if(_isOnline && !utils.isempty(url) && assets.length>0){
                    var url = url.replace("[recids]", assets.join(","));
                    var content = utils.getcontent(url, false);
                    return content;
                }else{
                    return "";
                }


            }

            function loadEntryURL(url){
                //document.getElementById('entryPage').innerHTML = '<object style="width:100%;height:900%" id="entryPage" type="text/html" data="'+url+'"><\/object>';
                window.open(url, "_blank");
            }

            //
            //
            //
            function execScript(ele)
            {
                var x = ele.getElementsByTagName("script");
                for(var i=0;i<x.length;i++)
                {
                    eval(x[i].text);
                }
            }

            //---------
            //
            // show current cache content
            //
            function cacheShow(){
                showPage('cache');

                var content = '';

                if (window.localStorage) {

                    var i, key, len , tot=0, mapcnt = 0, maptot = 0;
                    for (i = window.localStorage.length-1; i>=0; --i) {
                        key = window.localStorage.key(i);
                        len = window.localStorage.getItem(key).length;
                        tot = tot + len;
                        if(key == "version"){
                            _localVersion = Number(window.localStorage.getItem(key));
                        }else if(key.indexOf("olCache")==0){
                            mapcnt++;
                            maptot = maptot  + len;
                        }else{
                            content = content+key+"&nbsp;&nbsp;&nbsp;"+(Math.floor(len/1024))+" kB<br/>";
                            //content = content+key+"  "+len+"<br/>";
                        }
                    }
                    if(mapcnt>0){
                        content = "Map: "+mapcnt+" tiles. "+(Math.floor(maptot/1024))+" kB<br/><br/>" + content
                    }
                    content = "Version #"+_localVersion+"<br/>"+
                    window.localStorage.length+" entries. "+(Math.floor(tot/1024))+" kB<br/>" + content;

                }else{
                    content = 'Cache not supported';
                }

                document.getElementById('cache_content').innerHTML = content;

                document.getElementById('btnClearCache').style.display = _isOnline?"inline-block":"none";
                document.getElementById('btnSeedCache').style.display = _isOnline?"inline-block":"none";
            }

            //
            // remove all from cache
            //
            function cacheClear(){
                if (window.localStorage) {
                    window.localStorage.clear();
                }
                cacheShow();
            }

            //
            // update list of tours from server and cache it
            //
            function cacheSeedFromServer(e){
                loadTours(null); //load new list of tours from server side
                _localVersion = _serverVersion;
                cacheSeed();
            }

            //
            // cache current list of tours and its media (images) and map content
            //
            function cacheSeed(){

                initMapMain();
                cacheClear();

                if (!window.localStorage) {
                    return;
                }

                var _tours = tours.getTours(),
                k,i,united = "",
                ele = document.getElementById('cache_content'),
                keepvalue = utils.useCacheIfOnline;

                utils.useCacheIfOnline = true;

                localStorage.setItem("version", _localVersion);

                // Artem: Todo: Please indent the lsit (including Version #, number of entries, downlaoded images etc
                // a bit so it is not jammed up agaisnt left edge - say 20 pixels
                
                ele.innerHTML = "<div>Getting media/entries for:</div>";

                united = united + tours.getTourList(null,2);
                //save content for media and entry output
                for (k=0; k<_tours.length; k++){
                    ele.innerHTML = ele.innerHTML + _tours[k].title+"<br/>";
                    for (i=0; i<_tours[k].stops.length; i++){
                        _tours[k].stops[i].media = getMediaReport(url_report_media, _tours[k].stops[i].assets);
                        _tours[k].stops[i].entries = getMediaReport(url_report_entries, _tours[k].stops[i].assets);
                        united = united + _tours[k].stops[i].media + _tours[k].stops[i].entries;
                    }
                }
                //save tours as json string
                localStorage.setItem("alltours", JSON.stringify(_tours));

                //save images
                ele.innerHTML = ele.innerHTML + "<div>Saving images</div>";
                tab5 = document.getElementById("tab-5");
                tab5.innerHTML = united;
                execScript(tab5);
                //
                ele.innerHTML = ele.innerHTML + "<div>Save map locally</div>";
                map_ol.startMapSeed();

                utils.useCacheIfOnline = keepvalue;


                setTimeout(function(){
                    ele.innerHTML = ele.innerHTML + "<br/><button onclick=\"cacheShow()\">Show cache content</button>";
                    }, 1000);

                //cacheShow();
            }
            
            var isNearbyVisible = false;
            
            function showAllOrNearby(){
                
                if(isNearbyVisible){
                    $(".remote").css('display', 'block');
                    $("#toursAllOrNearby").html('Show Nearby Tours');
                }else{
                    $(".remote").css('display', 'none');
                    $("#toursAllOrNearby").html('Show All Tours');
                }
                
                isNearbyVisible = !isNearbyVisible;
                
                /*
                if($("#nearbyTours").css('display') == 'none'){
                    
                    $("#allTours").css('display', 'none');
                    $("#nearbyTours").css('display', 'block');
                    $("#toursAllOrNearby").html('Show All Tours');
                }else{
                    $("#nearbyTours").css('display', 'none');
                    $("#allTours").css('display', 'block');
                    $("#toursAllOrNearby").html('Show Nearby Tours');
                }
                 */
            }

        </script>

    </head>

    <body onLoad="setTimeout(function() { window.scrollTo(0, 1) }, 100); init(null)">
        <script type="text/javascript">
            var HEURIST = {};
        </script>

        <script type="text/JavaScript">

            /*
            if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(fetchcoords);
            } else {
            document.getElementById("warning").innerHTML = '<i>Unable to get position, maybe your browser does not support the HTML5 position function. Fixed coordinates are being used.</i>';
            fetchcoords(null);
            }
            */
            /*
            var pathwayPolygon;
            var polyline;
            var circle;
            var allPolylines;
            var allCircles;
            function calcPathOverlap(pathway) {
            var details = pathway.getAllDetails();
            if(!details[230]) return false; //ARTEM
            tmp1 = details[230][0].getWKT().split('('); // 230 = geographic object
            tmp2 = tmp1[2].split(')');
            segmentsLatLng = tmp2[0].split(",");
            var lngList = Array();
            var latList = Array();
            lngList.push(segmentsLatLng[0].split(" ")[0]);
            lngList.push(segmentsLatLng[1].split(" ")[0]);
            lngList.push(segmentsLatLng[2].split(" ")[0]);
            lngList.push(segmentsLatLng[3].split(" ")[0]);
            latList.push(segmentsLatLng[0].split(" ")[1]);
            latList.push(segmentsLatLng[1].split(" ")[1]);
            latList.push(segmentsLatLng[2].split(" ")[1]);
            latList.push(segmentsLatLng[3].split(" ")[1]);
            var east = 0;
            var west = 0;
            var north = 0;
            var south = 0;

            var tmpInd = 0;
            while(tmpInd < lngList.length) {
            if(east == 0 || west == 0) {
            east = lngList[tmpInd];
            west = lngList[tmpInd];
            }
            if(lngList[tmpInd] > east) {
            east = lngList[tmpInd];
            }
            if(lngList[tmpInd] < west) {
            west = lngList[tmpInd];
            }
            tmpInd++;
            }
            tmpInd = 0;
            while(tmpInd < latList.length) {
            if(south == 0 || north == 0) {
            south = latList[tmpInd];
            north = latList[tmpInd];
            }
            if(lngList[tmpInd] > south) {
            south = latList[tmpInd];
            }
            if(lngList[tmpInd] < north) {
            north = latList[tmpInd];
            }
            tmpInd++;
            }

            // TEST Paints a rectangle on the map, containing the selected pathway
            if(paintRectangle) {
            var corner1 = new google.maps.LatLng(south, west);
            var corner2 = new google.maps.LatLng(south, east);
            var corner3 = new google.maps.LatLng(north, east);
            var corner4 = new google.maps.LatLng(north, west);
            var rectangle = Array();
            rectangle.push(corner1);
            rectangle.push(corner2);
            rectangle.push(corner3);
            rectangle.push(corner4);
            pathwayPolygon = new google.maps.Polygon({
            paths: rectangle,
            strokeColor: "#FF0000",
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillOpacity: 0
            });
            pathwayPolygon.setMap(map);

            centerLng = (parseFloat(east)+parseFloat(west))/2;
            centerLat = (parseFloat(north)+parseFloat(south))/2;
            newCenter = new google.maps.LatLng(centerLat, centerLng);
            if(map) {
            map.setCenter(newCenter);
            map.setZoom(15);
            }
            }
            // END TEST

            if(isOverlap(east, north, south, west)) {
            return true;
            } else {
            return false;
            }
            }

            function isOverlap(e, n, s, w) {
            var xOverlap = valueOverlap(minLng, w, e) || valueOverlap(w, minLng, maxLng);
            var yOverlap = valueOverlap(minLat, s, n) || valueOverlap(s, minLat, maxLat);
            return xOverlap && yOverlap;
            }

            function valueOverlap(value, min, max) {
            return (value <= max) && (value >= min);
            }
            */
        </script>

        <div id="wrap" style="width:100%;height:100%;">
            <div id="header" style="width:100%"> Heurist Mobile for Tablet/Phone</div>

            <div id="listPage" style="display:block;">
                <div class="buttonBar">
                    <div id="toursAllOrNearby" class="backToListButton" onclick="showAllOrNearby()">Show All Tours</div>
                    <div id="btnCache2" onclick="cacheShow()" style="float:right">Downloaded data</div>
                </div>
                <div id="pathwayList">
                    <div id="warning"></div>
                    <div id="nearbyTours"><strong>Searching for tours...</strong></div>
                    <!-- <div id="allTours"></div> -->
                </div>
            </div>
            <div id="mapPage" style="display:none;">
                <div class="buttonBar">
                    <div id="backToListButton" class="backToListButton" onclick="showPage('list')">Tours List</div>
                    <div id="startButton" onclick="gotoStop(0)">Start Tour</div>
                    <!-- div id="status"></div>
                    <div id="hits"></div -->
                    <div id="btnCache" onclick="cacheShow()" style="float:right">Downloaded data</div>
                </div>
                <div id="map_canvas" style="position:absolute; left:5px; right:5px; top:70px;bottom:10px;"></div>
            </div>
            <div id="segmentPage" style="display:none;">
                <div class="buttonBar">
                    <div id="backToListButton" class="backToListButton" onclick="showPage('list')">&#8657;Tours List</div>
                    <div id="backToMapButton" class="backToMapButton" onclick="showPage('map')">&#8853; Overview Map</div>
                    <div id="previousSegmentButton" class="previousSegmentButton" onclick="gotoStop(-3)">&#8656; Previous</div>
                    <div id="nextSegmentButton" class="nextSegmentButton" onclick="gotoStop(-1)">Next &#8658;</div>
                </div>
                <div id="segmentVisit" class="segmentVisit">
                    <div id="activeStopTitle"></div>
                    <!-- div id="activeStopTitle"></div -->
                    <div id="tabs">
                        <ul>
                            <li><a href="#tab-1">Story</a></li>
                            <li><a href="#tab-2">Map</a></li>
                            <li><a href="#tab-3">Route</a></li>
                            <li><a href="#tab-4">Media</a></li>
                            <li><a href="#tab-5">More ...</a></li>
                        </ul>
                        <div id="tab-1">
                        </div>
                        <div id="tab-2">
                        </div>
                        <div id="tab-3">
                        </div>
                        <div id="tab-4">
                        </div>
                        <div id="tab-5">
                        </div>
                    </div>
                </div>
            </div>
            <div id="cachePage" style="display:none;">
                <div class="buttonBar">
                    <div id="backToListButton" onclick="showPage('list')">Tours List</div>
                    <!-- div id="backToMapButton" onclick="showPage('map')">Map</div -->
                    <div id="btnSeedCache" onclick="cacheSeed()">Download updated tour data</div>
                    <div id="btnClearCache" onclick="cacheClear()">Clear downloaded data</div>
                </div>
                <div id="cache_content" class="pathwayMap"></div>
            </div>
            <div id="messagePage" style="display:none;padding: 10px; text-align: center; vertical-align: middle;">
                <div id="divMessage"></div>
                <button id="btnMessage">Click me</button>
            </div>
            <div id="map_stop" style="position:absolute; display:none;left:5px; right:5px; top:150px;bottom:10px;"></div>
        </div>
    </body>

</html>